package com.ericsson.epc.modules.autocheck.thread;

import com.ericsson.epc.modules.autocheck.entity.EpcNetAutoCheck;
import com.ericsson.epc.modules.autocheck.entity.EpcVisAutoCheckLog;
import com.ericsson.epc.modules.autocheck.entity.EpcVisExcelModuleDetail;
import com.ericsson.epc.modules.autocheck.service.EpcEopsTemplateScheduleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class EpcEopsTemplateExecuteCmdThread implements Runnable {

	private Logger log;
	private String fetchDate;
	private CountDownLatch latch;
	private EpcNetAutoCheck net;
	private EpcEopsTemplateScheduleService scheduleService;
	private List<EpcVisExcelModuleDetail> visExcelModuleDetails;
	private String tpXmlPathTxt;

	public EpcEopsTemplateExecuteCmdThread(EpcNetAutoCheck net, List<EpcVisExcelModuleDetail> visExcelModuleDetails,
										   EpcEopsTemplateScheduleService scheduleService, CountDownLatch latch, String fetchDate, Logger log,String tpXmlPathTxt) {
		this.net = net;
		this.visExcelModuleDetails = visExcelModuleDetails;
		this.fetchDate = fetchDate;
		this.scheduleService = scheduleService;
		this.latch = latch;
		this.log = log;
		this.tpXmlPathTxt = tpXmlPathTxt;
	}

	@Override
	public void run() {
		try {
			dotask();
		} catch (Exception e) {
			log.error("dotask error", e);
		} finally {
			latch.countDown();
		}

	}

	private void dotask() {
		log.info("===============sub thread ====netId:" + net.getId() + " run start");
		for (EpcVisExcelModuleDetail moduleDetail : visExcelModuleDetails) {
			String command = "/usr/bin/perl -w /opt/Ericsson/core/bin/eops.pl";
			command += " -ip " + net.getIpadr() + " -user " + net.getUsername1() + " -password '" + net.getPassword1()
					+ "' -conf_file " + tpXmlPathTxt + moduleDetail.getExcelId() + "_"
					+ moduleDetail.getModuleId() + ".txt -rootpassword '" + net.getPassword2() + "'";
			log.info("netId========" + net.getId() + "command======" + command);
			EpcVisAutoCheckLog autoCheckLog = execAutoTemplateCheckCmd(command, net.getId(), moduleDetail.getExcelId());
			autoCheckLog.setTemplateType(moduleDetail.getTemplateType().toLowerCase().substring(0,
					moduleDetail.getTemplateType().length() - 3));
			// 过滤命令前的其它信息 start
			if (null != autoCheckLog && StringUtils.isNotBlank(autoCheckLog.getCheckResult())
					&& !autoCheckLog.getCheckResult().equals("exception")) {
				String filterResult = filterGarbageMsg(moduleDetail, autoCheckLog);
				if (null != filterResult) {
					autoCheckLog.setCheckLog(filterResult);
				}
			}
			//// 过滤命令前的其它信息 end
			if (StringUtils.isNotBlank(autoCheckLog.getCheckLog())) {
				scheduleService.insertAutoCheckLog(autoCheckLog);
			}
		}

		log.info("================= AutoCheckTemplateServiceTask end  ========");
	}

	private EpcVisAutoCheckLog execAutoTemplateCheckCmd(String command, Long netId, Integer excelId) {
		Process proc = null;
		String[] cmd = new String[3];
		cmd[0] = "sh";
		cmd[1] = "-c";
		cmd[2] = command;
		// System.out.println(cmd[2]);
		BufferedReader br = null;
		String line = null;
		StringBuilder sb = new StringBuilder();
		EpcVisAutoCheckLog autoCheckLog = new EpcVisAutoCheckLog();
		autoCheckLog.setNetId(String.valueOf(netId));
		autoCheckLog.setExcelId(excelId);
		autoCheckLog.setCheckTime(this.fetchDate);

		try {
			proc = Runtime.getRuntime().exec(cmd);// 测试时需要注释掉

			br = new BufferedReader(new InputStreamReader(proc.getInputStream()), 10 * 1024 * 1024);// 测试时需要注释掉
			// br = readFile("D:/test2.txt");//测试代码
			Thread.sleep(200);
			while ((line = br.readLine()) != null) {
				sb.append(line).append("||");
				// log.info(line);
				// 成功
				if (line.contains("EOPS RUN SUCCESS")) {
					autoCheckLog.setCheckResult("ok");
				} else if (line.contains("<font color=\"red\">")) { // 异常 低于门限
					autoCheckLog.setCheckResult("Nok");
				} else {
					autoCheckLog.setCheckResult("exception"); // 出错 程序没有正确执行
				}
			}
			autoCheckLog.setCheckLog(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (proc != null) {
				proc.destroy();
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return autoCheckLog;
	}

	/**
	 * 过滤返回结果中的无用头信息（ok,Nok状态数据）
	 * 
	 * @param moduleDetail
	 * @param autoCheckLog
	 * @return String 过滤后的结果
	 */
	public String filterGarbageMsg(EpcVisExcelModuleDetail moduleDetail, EpcVisAutoCheckLog autoCheckLog) {
		if (StringUtils.isNotBlank(autoCheckLog.getCheckLog()) && !"".equals(autoCheckLog.getCheckLog())
				&& null != moduleDetail && StringUtils.isNotBlank(moduleDetail.getConfCmd())) {
			int startSize = autoCheckLog.getCheckLog().indexOf(moduleDetail.getConfCmd())
					+ moduleDetail.getConfCmd().length();
			return autoCheckLog.getCheckLog().substring(startSize);
		}
		return null;
	}

}
